package nameless.aistudy.domain.service.subjects.english.vocabulary;

import lombok.RequiredArgsConstructor;
import nameless.aistudy.domain.model.subjects.english.vocabulary.book.VocabularyBook;
import nameless.aistudy.domain.model.subjects.english.vocabulary.book.VocabularyBookRepo;
import nameless.aistudy.domain.model.subjects.english.vocabulary.dto.VocabularyBookDTO;
import nameless.aistudy.domain.model.subjects.english.vocabulary.dto.WordDetailDTO;
import nameless.aistudy.domain.model.subjects.english.vocabulary.utils.ContentFilterUtil;
import nameless.aistudy.domain.model.subjects.english.vocabulary.word.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

@Service
@RequiredArgsConstructor
public class VocabularyInsertService {
    // 注入所有Repo
    private final VocabularyBookRepo vocabularyBookRepo;
    private final WordRepo wordRepo;
    private final WordGroupOneRepo wordGroupRepo;
    private final WordDefinitionOneRepo wordDefinitionRepo;
    private final SentenceRepo sentenceRepo;
    private final BookWordRelationRepo bookWordRelationRepo;

    /**
     * 统一入口：检查词汇本是否存在 → 不存在则创建 → 存在/创建后添加单词
     * @param dto 包含词汇本名称和单词列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void createOrAddWords(VocabularyBookDTO dto) {
        // 1. 校验词汇本名称不为空
        String bookName = dto.getBookName();
        if (bookName == null || bookName.trim().isEmpty()) {
            throw new RuntimeException("词汇本名称不能为空");
        }

        // 2. 检查词汇本是否已存在（根据名称）
        VocabularyBook existingBook = vocabularyBookRepo.selectByBookName(bookName);
        Integer bookId;

        if (existingBook != null) {
            // 词汇本已存在：直接使用现有ID
            bookId = existingBook.getId();
        } else {
            // 词汇本不存在：先创建（含名称合规检查）
            if (ContentFilterUtil.hasInvalidContent(bookName)) {
                throw new RuntimeException("词汇本名称包含违规信息，请修改后重试");
            }
            VocabularyBook newBook = new VocabularyBook();
            newBook.setBookName(bookName);
            vocabularyBookRepo.insert(newBook);
            bookId = newBook.getId(); // 获取新创建的ID
        }

        // 3. 往词汇本添加单词（复用添加逻辑，含内容检查）
        dto.setBookId(bookId); // 设置bookId
        this.addWordsToBook(dto);
    }

    /**
     * 创建词汇本（单独调用接口）
     */
    public VocabularyBook createVocabularyBook(VocabularyBookDTO dto) {
        String bookName = dto.getBookName();
        if (bookName == null || bookName.trim().isEmpty()) {
            throw new RuntimeException("词汇本名称不能为空");
        }
        // 合规检查
        if (ContentFilterUtil.hasInvalidContent(bookName)) {
            throw new RuntimeException("词汇本名称包含违规信息，请修改后重试");
        }
        VocabularyBook book = new VocabularyBook();
        book.setBookName(bookName);
        vocabularyBookRepo.insert(book);
        return book;
    }

    /**
     * 向指定词汇本添加单词（含内容合规检查）
     */
    @Transactional(rollbackFor = Exception.class)
    public void addWordsToBook(VocabularyBookDTO dto) {
        Integer bookId = dto.getBookId();
        // 校验词汇本存在
        VocabularyBook book = vocabularyBookRepo.selectById(bookId);
        if (book == null) {
            throw new RuntimeException("词汇本不存在，请先创建（bookId=" + bookId + "）");
        }

        List<WordDetailDTO> wordList = dto.getWords();
        if (wordList == null || wordList.isEmpty()) {
            throw new RuntimeException("单词列表不能为空");
        }

        // 遍历单词列表，逐个处理
        for (WordDetailDTO wordDTO : wordList) {
            // ===== 内容合规性检查 =====
            if (ContentFilterUtil.hasInvalidContent(wordDTO.getSpell())) {
                throw new RuntimeException("单词拼写包含违规信息，请修改后重试");
            }
            if (ContentFilterUtil.hasInvalidContent(wordDTO.getChinese())) {
                throw new RuntimeException("中文释义包含违规信息，请修改后重试");
            }
            if (ContentFilterUtil.hasInvalidContent(wordDTO.getCategory())) {
                throw new RuntimeException("词性包含违规信息，请修改后重试");
            }
            if (ContentFilterUtil.hasInvalidContent(wordDTO.getBriefDefinitions())) {
                throw new RuntimeException("单词释义包含违规信息，请修改后重试");
            }
            if (ContentFilterUtil.hasInvalidContent(wordDTO.getExample())) {
                throw new RuntimeException("例句包含违规信息，请修改后重试");
            }

            // ① 检查单词是否已存在（避免重复插入）
            Word existingWord = wordRepo.selectBySpell(wordDTO.getSpell());
            Integer wordId;

            if (existingWord != null) {
                wordId = existingWord.getId();
                // 检查是否已关联到当前词汇本，避免重复关联
                BookWordRelation relation = bookWordRelationRepo.selectByBookIdAndWordId(bookId, wordId);
                if (relation != null) {
                    continue; // 已关联，跳过
                }
            } else {
                // 新增单词
                Word word = new Word();
                word.setSpell(wordDTO.getSpell());
                word.setAssociationTips(wordDTO.getChinese());

                // 处理音标
                if (wordDTO.getPronunciation() != null) {
                    String[] pronunciations = wordDTO.getPronunciation().split(" / ");
                    if (pronunciations.length >= 1) {
                        word.setUkPronunciationIpa(pronunciations[0].trim());
                    }
                    if (pronunciations.length >= 2) {
                        word.setUsPronunciationIpa(pronunciations[1].trim());
                    }
                }
                wordRepo.insert(word);
                wordId = word.getId();
            }

            // ② 插入词汇本-单词关联
            BookWordRelation relation = new BookWordRelation();
            relation.setBookId(bookId);
            relation.setWordId(wordId);
            bookWordRelationRepo.insert(relation);

            // ③ 处理词性、释义、例句
            if (wordDTO.getCategory() != null && !wordDTO.getCategory().isEmpty()) {
                WordGroup wordGroup = new WordGroup();
                wordGroup.setWordId(wordId);
                wordGroup.setCategory(wordDTO.getCategory());
                wordGroup.setIsDeleted(0);
                wordGroupRepo.insert(wordGroup);
                Integer groupId = wordGroup.getId();

                if (wordDTO.getBriefDefinitions() != null && !wordDTO.getBriefDefinitions().isEmpty()) {
                    WordDefinition definition = new WordDefinition();
                    definition.setGroupId(groupId);
                    definition.setDefinition(wordDTO.getBriefDefinitions());
                    definition.setIsDeleted(0);
                    wordDefinitionRepo.insert(definition);
                }

                if (wordDTO.getExample() != null && !wordDTO.getExample().isEmpty()) {
                    Sentence sentence = new Sentence();
                    sentence.setTypeId(groupId);
                    sentence.setContent(wordDTO.getExample());
                    sentence.setIsDeleted(0);
                    sentenceRepo.insert(sentence);
                }
            }
        }
    }

}
